/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package coursesmaritimes.obtention.client;

import java.net.*;
import java.io.*;
/**
 * Les socket niveau client
 * @author csuma
 * @version 0.2 
 */
public class SocketClient {

    private Socket socket = null;
    private DataInputStream streamIn = null;
    private DataOutputStream streamOut = null;
    public String server;
    public int serverPort;

    /**
     * Constructeur.
     * Le socket est construit avec l'adresse de la machine locale
     */
    public SocketClient() {
        server = "127.0.0.1";
        serverPort = 7500;
    }

    /**
     * Demarrer la communication
     */
    public void start() {
        try {
            socket = new Socket(server, serverPort);
            streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            streamOut = new DataOutputStream(socket.getOutputStream());
            System.out.println("Connected: " + socket);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    /**
     * Arreter la communication
     */
    public void stop() {
        try {
            if (streamIn != null) {
            streamIn.close();
        }
            if (streamOut != null) {
                streamOut.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException ioe) {
            System.out.println("Error closing ...");
        }
    }

    /**
     * Lit un message depuit le serveur
     * @return le message lu
     */
      public String getMessage() {
        String line=null;
        try {
            line = streamIn.readUTF();
        } catch (IOException ioe) {
           System.out.println(ioe.getMessage() + " getM cli");
        }
        return line;
    }

      /**
       * Envoie un message au serveur
       * @param msg : le message à envoyer
       */
    public void sendMessage(String msg) {
        try {
            streamOut.writeUTF(msg);
            streamOut.flush();
        } catch (Exception ex) {
            System.out.println(ex.getMessage() + "send cli");
        }
    }
}
